(function() {
	var HZBank = this.HZBank || (this.HZBank = {});
	var View = HZBank.View = HZBank.View || (this.HZBank.View = {});
	var $ = this.$ || this.jQuery;
	var Backbone = this.Backbone;
	var logger = HZBank.logger;
	/***add by zhanghuan  ------去掉对backbone的依赖****/
	var viewId = 0;
	var delegateEventSplitter = /^(\S+)\s*(.*)$/;
	function getplugin(){
		var plugin = function(t){
			this.id = this.getID();
			this.ensureEle();
			this.initialize.apply(this,arguments);
			this.undelegateEvents();
			this.delegateEvents();
		}
		plugin.prototype ={
			initialize:function(){
				if (this.init) {
					this.init(arguments);
				}
			},
			ensureEle:function(){
				this.$el = $(this.el);
			},
			init:function(){},
			events:{},
			undelegateEvents:function(){
				if(!this.el){
					return;
				}
				this.$el = $(this.el);
				this.$el.off('.delegateEvents' + this.id);
			    return this;
			},
			getID:function(){
				 var id = ++viewId + '';
				 return 'view' + id;
			},
			delegateEvents:function(){
				if(!this.el){
					return;
				}
				this.$el = $(this.el);
				var events = this.events;
				 for (var key in events) {
				        var method = events[key];
				        if (!$.isFunction(method)) method = this[events[key]];
				        if (!method) continue;

				        var match = key.match(delegateEventSplitter);
				        var eventName = match[1], selector = match[2];
				        method = _.bind(method, this);
				        eventName += '.delegateEvents' + this.id;
				        if (selector === '') {
				          this.$el.on(eventName, method);
				        } else {
				          this.$el.on(eventName, selector, method);
				        }
				      }
			}
		}
		return plugin;
	}
	var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
	 var push             = ArrayProto.push,
	     slice            = ArrayProto.slice,
	     concat           = ArrayProto.concat,
	     toString         = ObjProto.toString,
	     hasOwnProperty   = ObjProto.hasOwnProperty;
	 var
	    nativeForEach      = ArrayProto.forEach,
	    nativeMap          = ArrayProto.map,
	    nativeReduce       = ArrayProto.reduce,
	    nativeReduceRight  = ArrayProto.reduceRight,
	    nativeFilter       = ArrayProto.filter,
	    nativeEvery        = ArrayProto.every,
	    nativeSome         = ArrayProto.some,
	    nativeIndexOf      = ArrayProto.indexOf,
	    nativeLastIndexOf  = ArrayProto.lastIndexOf,
	    nativeIsArray      = Array.isArray,
	    nativeKeys         = Object.keys,
	    nativeBind         = FuncProto.bind;
	var _ = {
			bind:function(func, context) {
				    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
				    var args = slice.call(arguments, 2);
				    return function() {
				      return func.apply(context, args.concat(slice.call(arguments)));
				    };
				}
	}
	View.Base = {
			extend :function(option){
				var demo  = getplugin();
				$.extend(demo.prototype, option);
				return demo;
			}	
	}
	View.Error = View.Base.extend({
		className : 'desktop-error-msg',
		initialize : function() {

		}
	});
	var options = {
			className : 'form',
			initialize : function() {
				this.initForm();
				if (this.init) {
					this.init(arguments);
				}
			},
			initCallBack : $.noop,
			initForm : function() {
				var _this = this;
				// init input
				$('input[data-type="cardNum"]').each(function(){
					var myVal = HZBank.Utils.Rules.cardNum($(this).val());
					$(this).val(myVal);
					if($(this).val().length >= 23){
						var setVal = $(this).val().substring(0, 23);
						$(this).val(setVal);
					}
				});
				$('input[data-type="cardNum"]').css({'font-weight':'bold'}).unbind('input propertychange').bind('input propertychange',function(){
					var myVal = HZBank.Utils.Rules.cardNum($(this).val());
					$(this).val(myVal);
					if($(this).val().length >= 23){
						var setVal = $(this).val().substring(0, 23);
						$(this).val(setVal);
					}
				});
				// init checkbox
				$('input[type=checkbox]', this.$el).checkbox();
				// init radiobutton
				$('input[type=radio]', this.$el).radio();
				// init select

				var $all = $('select:not([multiple],[data-ignore="true"]), select[multiple][data-type="multiple-select"]:not([data-ignore="true"])', this.$el), //
					$el = $all.filter('[data-key]'),
					$nel = $all.not($el);
				
				var types = $.makeArray($el.map(function(i, el) {
					var $this = $(el);
					if ($this.parent().is('.ui-select')) {
						return;
					}
					////console.log($this.data('parentId'));
					return {
						key : $this.data('key'),
						table : $this.data('table') || 'para',
						parentId : $this.data('parentId') || $this.data('parentid')||'false'
					};
				}));
				
				HZBank.Utils.getSelects({
					els : $el,
					types : types,
					success : function() {
						$el.select();
						_this.initCallBack();
					}
				});
				
				$nel.each(function() {
					$this = $(this);
					if (!$this.parent().is('.ui-select')) {
						$this.select();
					}
				});
				
//				$('select:not([multiple],[data-ignore="true"])', this.$el).select();
//				$('select[multiple][data-type="multiple-select"]:not([data-ignore="true"])', this.$el).select();
			
				// init date
				$('input[data-type=date]', this.$el).datetimepicker({
					pickTime : false
				});
				$('input[data-type=time]', this.$el).datetimepicker({
					pickDate : false
				});
				$('input[data-type="date-time"]', this.$el).datetimepicker();
			},
			/**
			 * 
			 * 将FORM内部所有表单域封装为JSON对象
			 * JSON中key为表单名
			 * 
			 * @param form{String/jQuery}
			 *            form名，遵循jQuery选择器使用方式
			 * @param quick{boolean}
			 *            默认为false
			 *            true 快速封装，不会对表单名中带有.的表单域进行深度封装
			 *            
			 */
			getJSON : function(form, quick) {
				if (typeof form === 'boolean') {
					quick = form;
					form = '';
				}
				if (form) {
					form = this.$el.is(form) ? this.$el : $(form, this.$el);
				} else {
					form = this.$el.is('form') ? this.$el : $('form', this.$el);
				}
				return HZBank.Utils.form2json(form, quick);
			},
			getJSONString : function(form, quick) {
				return JSON.stringify(this.getJSON(form, quick));
			},
			resetWidget : function() {
				// reset checkbox
				$('input[type=checkbox]', this.$el).checkbox('reset');
				// reset radiobutton
				$('input[type=radio]', this.$el).radio('reset');
				// reset select
				$('select:not([multiple],[data-ignore="true"],[role="listbox"],[disabled])', this.$el).select('reset');
			},
			
			/*
			 * Check required fields
			 * 
			 * @param el
			 *		传入区域元素
			 * 
			 * @param trim
			 * 		是否需要去掉前后空字符进行验证，默认去掉空格（true）
			 *  
			 * @param show
			 * 		是否需要显示错误提示，默认为不显示（false）
			 */
			check : function(el, trim, show) {
				var ars2 =(el ? this.$el.find(el) : this.$el).find('input[type=text],textarea');
				var ars = (el ? this.$el.find(el).find('.required') : this.$el.find('.required')).filter('input,select,textarea');
				var pass = true;
				if (trim !== false) {
					trim = true;
				}
				for ( var i = 0; i < ars.length; i++) {
					var el = ars.eq(i);
					if ((trim && $.trim(el.val()) == '') || el.val() == '') {
						pass = false;
						if (show) {
							if (el.is('select')) {
								el.select('error', true);
							} else {
								el.addClass('error');
							}
						}
					} else {
						if (el.is('select')) {
							el.select('error', false);
						} else {
							el.removeClass('error');
						}
					}
				}
				//进行正则表达式的验证
				
				for(var i=0;i<ars2.length; i++){
					var el = ars2.eq(i);
					var v= el.val(),pattern = el.attr('pattern');
					if(v && pattern  ){
						var re= new RegExp(pattern);
						if(!re.test(v) && el.is('input')){
							el.addClass('error');
							pass = false;
						}
					}
				}
				return pass;
			},
			/*
			 * Check required fields
			 * 
			 * @param el
			 *		传入区域元素
			 * 
			 * @param trim
			 * 		是否需要去掉前后空字符进行验证，默认去掉空格（true）
			 *  
			 */
			checkRequied : function(el, trim) {
				return this.check(el, trim, true);
			},
			/*
			 * 重置表单元素
			 */
			reset : function() {
				
				/*if (this.$el.is('form')) {
					this.$el.get(0).reset();
				} else {
					this.$el.find('form').get(0).reset();
					logger.warn('This is not a form!');
				}*/
				this.$el.find('input[type=text]').val('');
				this.resetWidget();
			},
			/*
			 * 移除错误提示
			 */
			clearError : function() {
				this.$el.find('.error').removeClass('error');
			}
	}
	View.Form = {
			extend :function(option){
				var demo  = getplugin();
				$.extend(demo.prototype, options,option);
				return demo;
			}	
	};
	this.HZBank = HZBank;
})(this);